//
//  YSY_Player_ViewController.m
//  GoodManNews
//
//  Created by dllo on 16/1/15.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "YSY_Player_ViewController.h"
#import "YSY_Player_View.h"

#define VIDEOURL(vid) [NSString stringWithFormat:@"http://box.dwstatic.com/apiVideoesNormalDuowan.php?action=f&vid=%@", vid]
@interface YSY_Player_ViewController ()
@property (nonatomic, retain) YSY_Player_View *playerView;

@property (nonatomic, copy) NSString *duration;         //总时间
@property (nonatomic, retain) NSMutableArray *URLarr;   //0:流畅 1:高清 2:超清

@property (nonatomic, retain) AVPlayer *player;     //播放对象
@property (nonatomic, retain) AVPlayerItem *playerItem;     //资源管理对象
@property (nonatomic, retain) AVPlayerLayer *playerLayer;   //播放图层
@property (nonatomic, retain) UIView *playerLayerView;      //播放图层view
@property (nonatomic, retain) UIView *controlToolView;      //控制工具view
@property (nonatomic, retain) UIProgressView *videoProgress; //缓冲进度
@property (nonatomic, retain) UISlider *videoPlayProgress;   //播放进度
@property (nonatomic, retain) UISlider *videoVolumeSlider;   //声音
@property (nonatomic, retain) UIButton *startOrStop_btn;     //播放按钮
@property (nonatomic, retain) UIButton *fullScreen_btn;      //全屏按钮
@property (nonatomic, retain) UILabel *currentTime;         //当前时间
@property (nonatomic, retain) UILabel *totalTime;           //总时间
@property (nonatomic, assign) CGPoint point;                //点击时候的点
@property (nonatomic, retain) UITapGestureRecognizer *tap;  //全屏时候点击出现控制view
@property (nonatomic, copy) NSString *imageURL;             //图片链接
@property (nonatomic, retain)  UIView *juhauV;              //菊花视图

@end

@implementation YSY_Player_ViewController
- (void)dealloc
{
    [self removeObserverFromPlayerItem:self.player.currentItem];
    [self removeNotification];
    
    
    [_videlVid release];
    [_juhauV release];
    [_player release];
    [_playerItem release];
    [_playerLayer release];
    [_playerLayerView release];
    [_controlToolView release];
    [_videoPlayProgress release];
    [_videoProgress release];
    [_videoVolumeSlider release];
    [_startOrStop_btn release];
    [_fullScreen_btn release];
    [_currentTime release];
    [_totalTime release];
    [_URLarr release];
    [_imageURL release];
    [super dealloc];
}


+ (instancetype)shareData {
    static YSY_Player_ViewController *hero = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hero = [[YSY_Player_ViewController alloc] init];
    });
    return hero;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction)];
    self.startOrStop_btn.enabled = NO;
    //取数据
    [self getData];
}
//创建player
- (void)createPlayer {

    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.URLarr[0]]];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    [self createPlayerView];
    
    [self addobserverToPlayerItem];
    
}
#pragma mark - 取数据
- (void)getData  {
    
        [GoodManNews_AFNetTool getNetWithURL:VIDEOURL(self.videlVid) body:nil headFile:nil responseStyle:WBNJSON success:^(NSURLSessionDataTask *task, id responseObject) {
            
            NSMutableDictionary *dic = responseObject[@"result"];
            //总时间
            self.duration = dic[@"items"][@"350"][@"duration"];
            self.URLarr = [NSMutableArray array];
            for (NSString *key in dic[@"items"]) {
                [self.URLarr addObject:dic[@"items"][key][@"transcode"][@"urls"][0]];
            }
            
            for (NSString *url in self.URLarr) {
                NSLog(@"%@", url);
            }
            self.imageURL = dic[@"cover"];
            //创建播放器
            [self createPlayer];
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
            
        }];
    
}

#pragma mark - 播放器视图
- (void)createPlayerView {
    
    
    
    
    self.playerLayerView = [UIView new];
    self.playerLayerView.backgroundColor  = [UIColor whiteColor];
    [self.view addSubview:self.playerLayerView];
    self.playerLayerView.frame = CGRectMake(0, 0, WIDTH, HEIGHT / 3);
    
   
    
    
    
    UIPanGestureRecognizer *pan  = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [self.playerLayerView addGestureRecognizer:pan];
    [pan release];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT  /3);
    self.playerLayer.backgroundColor = [[UIColor groupTableViewBackgroundColor] CGColor];
    [self.playerLayerView.layer addSublayer:self.playerLayer];
    

    UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.playerLayerView.frame];
    imageV.tag = 20001;
    [imageV sd_setImageWithURL:[NSURL URLWithString:self.imageURL] placeholderImage:[UIImage imageNamed:@"zhanwei"]];
    imageV.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:imageV];
    [imageV release];
    
    
    self.controlToolView = [UIView new];
    self.controlToolView.backgroundColor  = [UIColor grayColor];
    self.controlToolView.alpha = 0.6;
    [self.view addSubview:self.controlToolView];
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT  /3);
//    [self.controlToolView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.and.right.equalTo(self.view);
//        make.top.equalTo(self.playerLayerView.mas_bottom);
//        make.height.mas_equalTo(HEIGHT / 12);
//    }];
    self.controlToolView.frame = CGRectMake(0, self.playerLayerView.frame.origin.y + self.playerLayerView.frame.size.height, WIDTH, HEIGHT / 12);
    
    
    self.startOrStop_btn = [UIButton new];
    [self.startOrStop_btn setImage:[UIImage imageNamed:@"player_start"] forState:UIControlStateNormal];
    [self.startOrStop_btn setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateSelected];
    [self.startOrStop_btn addTarget:self action:@selector(startOrStopAction:) forControlEvents:UIControlEventTouchUpInside];
//    self.startOrStop_btn.backgroundColor = [UIColor yellowColor];
    [self.controlToolView addSubview:self.startOrStop_btn];
    [self.startOrStop_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.controlToolView);
        make.top.equalTo(self.controlToolView);
        make.bottom.equalTo(self.controlToolView);
        make.width.mas_equalTo(WIDTH / 8);
    }];
    
    self.currentTime = [UILabel new];
    self.currentTime.textAlignment  = NSTextAlignmentCenter;
    self.currentTime.text = @"00:00";
//    self.currentTime.backgroundColor = [UIColor greenColor];
    [self.controlToolView addSubview:self.currentTime];
    [self.currentTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.startOrStop_btn.mas_right);
        make.centerY.equalTo(self.controlToolView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(50, HEIGHT / 12));
    }];
    
    self.videoProgress = [UIProgressView new];
    self.videoProgress.backgroundColor  = [UIColor magentaColor];
    [self.controlToolView addSubview:self.videoProgress];
    [self.videoProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.currentTime.mas_right);
        make.centerY.equalTo(self.controlToolView.mas_centerY);
        make.width.mas_equalTo(WIDTH / 2);
        make.height.mas_equalTo(@2);
    }];
    
    self.videoPlayProgress = [UISlider new];
    [self.videoPlayProgress addTarget:self action:@selector(videoProgressAction:) forControlEvents:UIControlEventValueChanged];
    [self.controlToolView addSubview:self.videoPlayProgress];
    [self.videoPlayProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.videoProgress);
        make.height.mas_equalTo(@2);
    }];
    
    self.totalTime = [UILabel new];
    self.totalTime.textAlignment  = NSTextAlignmentCenter;
    self.totalTime.text = @"00:00";
//    self.totalTime.backgroundColor = [UIColor greenColor];
    [self.controlToolView addSubview:self.totalTime];
    [self.totalTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.videoProgress.mas_right);
        make.centerY.equalTo(self.controlToolView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(50, HEIGHT / 12));
        
    }];
    
    self.fullScreen_btn = [UIButton new];
    [self.fullScreen_btn setImage:[UIImage imageNamed:@"player_quanping"] forState:UIControlStateNormal];
    [self.fullScreen_btn setImage:[UIImage imageNamed:@"player_quxiaoquanping"] forState:UIControlStateSelected];
    [self.fullScreen_btn addTarget:self action:@selector(fullScreenAction:) forControlEvents:UIControlEventTouchUpInside];
//    self.fullScreen_btn.backgroundColor = [UIColor yellowColor];
    [self.controlToolView addSubview:self.fullScreen_btn];
    [self.fullScreen_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.controlToolView);
        make.bottom.equalTo(self.controlToolView);
        make.left.equalTo(self.totalTime.mas_right);
        make.right.equalTo(self.controlToolView);
        
    }];
    
    
    self.juhauV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 12 * 5)];
    self.juhauV.backgroundColor = [UIColor grayColor];
    self.juhauV.alpha = 0.5;
    [self.view addSubview:self.juhauV];
    [_juhauV release];
    
    UIActivityIndicatorView *indivatorV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    indivatorV.center = self.juhauV.center;
    [self.juhauV addSubview:indivatorV];
    [indivatorV release];
    [indivatorV startAnimating];
    
}




#pragma mark - 播放和全屏 按钮方法
//播放
- (void)startOrStopAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.player play];
        NSLog(@"开始");
        if ([self.view viewWithTag:20001]) {
            UIImageView *imageV = [self.view viewWithTag:20001];
            [imageV removeFromSuperview];
        }
        
        
        
    }else {
        [self.player pause];
    }
    
}
//全屏
- (void)fullScreenAction:(UIButton *)sender {
    
    if (sender.selected) {//取消全屏
        //显示Tabbar
        self.tabBarController.tabBar.hidden = NO;
        //显示导航栏navigationBar
        self.navigationController.navigationBarHidden = NO;
        [self.tap removeTarget:self action:@selector(tapAction:)];
        self.view.transform = CGAffineTransformMakeRotation(0 *M_PI / 180.0);
        self.playerLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT / 3);

        self.playerLayerView.frame = CGRectMake(0, 0, WIDTH, HEIGHT / 3);

        NSLog(@"%f", self.playerLayerView.frame.origin.y + self.playerLayerView.frame.size.height);
        self.controlToolView.frame = CGRectMake(0, HEIGHT / 3, WIDTH, HEIGHT / 12);
        [self.videoProgress mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.currentTime.mas_right);
            make.centerY.equalTo(self.controlToolView.mas_centerY);
            make.width.mas_equalTo(WIDTH / 2);
            make.height.mas_equalTo(@2);
        }];
        NSLog(@"%f", self.controlToolView.frame.origin.y);
 
    }else {//全屏
        //隐藏Tabbar
        self.tabBarController.tabBar.hidden = YES;
        //隐藏导航栏navigationBar
        self.navigationController.navigationBarHidden = YES;
        self.view.transform = CGAffineTransformMakeRotation(M_PI_2);
        
        self.playerLayer.frame = CGRectMake(0, 0, HEIGHT, WIDTH);;
        [self.videoProgress mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.currentTime.mas_right);
            make.centerY.equalTo(self.controlToolView.mas_centerY);
            make.width.mas_equalTo(self.view.bounds.size.height - (self.startOrStop_btn.bounds.size.width + self.currentTime.bounds.size.width) * 2);
            make.height.mas_equalTo(@2);
        }];
        
        self.controlToolView.frame = CGRectMake(0, WIDTH - HEIGHT / 12, HEIGHT, HEIGHT / 12);
        
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self.playerLayerView addGestureRecognizer:self.tap];
        [_tap release];
    }
    sender.selected = !sender.selected;
    
    
}
- (void)tapAction:(UITapGestureRecognizer *)sender {
    self.controlToolView.hidden = !self.controlToolView.hidden;
}

- (void)leftBarButtonItemAction {
    [self removeNotification];
    [self removeObserverFromPlayerItem:self.player.currentItem];
    //重新请求新的置空就可以
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [self.navigationController popViewControllerAnimated:YES];
//    [[self.navigationController popToRootViewControllerAnimated:YES];
}
//屏幕不可以旋转
- (BOOL)shouldAutorotate
{
    return NO;
}
// 当前支持的转屏幕方向
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscapeRight;
}
#pragma mark - Player 通知
//playerItem 添加监听
- (void)addobserverToPlayerItem {
    NSLog(@"添加监听");
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}

-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
#pragma mark - KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"] ) {
        if ([playerItem status] == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"可以播放了");
            
            if (self.juhauV) {
                [self.juhauV removeFromSuperview];
            }
            self.startOrStop_btn.enabled = YES;
            //
            //总秒数
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;
            self.videoPlayProgress.maximumValue = totalSecond;
            //此处可以设置时间条 进行监听
            [self monitoringPlayback:playerItem];
            
            //计算时间
            self.totalTime.text = [self changeTime:totalSecond];
            
            
            
        }else if ([playerItem status] == AVPlayerItemStatusFailed) {
            NSLog(@"请求失败");
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        //计算缓存进度
        NSTimeInterval timeInterval = [self availableDuration];
        NSLog(@"+++++++++%lf", timeInterval);
        [self.videoProgress setProgress:timeInterval/(playerItem.duration.value/playerItem.duration.timescale) animated:YES];
    }
    
}

#pragma mark - 通知
/**
 *  播放完成
 */
- (void)addNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidEnd) name:AVPlayerItemFailedToPlayToEndTimeNotification object:self.playerItem];
}
/**
 *  移除通知
 */
-(void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - 私有方法
//计算时间
-(NSString *)changeTime:(CGFloat) time {
    int tempTime = (int)time;
    int m = tempTime / 60;
    int s = tempTime % 60;
    NSString *mm = nil;
    NSString *ss = nil;
    if(m >= 10 ) {
        mm = [NSString stringWithFormat:@"%d", m];
    }else {
        mm = [NSString stringWithFormat:@"0%d", m];
    }
    
    if(s >= 10 ) {
        ss = [NSString stringWithFormat:@"%d", s];
    }else {
        ss = [NSString stringWithFormat:@"0%d", s];
    }
    
    return [NSString stringWithFormat:@"%@:%@", mm, ss];
    
}

//播放结束
- (void)playerDidEnd {
    NSLog(@"播放完成");
}
//计算缓存进度
- (NSTimeInterval)availableDuration {
    
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    //缓冲开始
    float startSecond =  CMTimeGetSeconds(timeRange.start);
    //缓冲总
    float durationSecond = CMTimeGetSeconds(timeRange.duration);
    //计算缓冲中总进度
    NSTimeInterval result = startSecond + durationSecond;
    return result;
}

//播放后监听,更新播放进度条
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:NULL usingBlock:^(CMTime time) {
        
        CGFloat currentSecond = playerItem.currentTime.value / playerItem.currentTime.timescale;
        self.currentTime.text = [self changeTime:currentSecond];
        [self.videoPlayProgress setValue:currentSecond animated:YES];
        
    }];
    
}

//快进 快退
- (void)videoProgressAction:(UISlider *)sender  {
    [self.player seekToTime:CMTimeMake(self.videoPlayProgress.value, 1)];
}

//拖动手势:声音 和快进
-(void)panAction:(UIPanGestureRecognizer *)sender {
    CGPoint touchPoint = [sender locationInView:sender.view];
    
    /**
     *  声音++++
     */
    if (touchPoint.x - self.point.x < 10 && (touchPoint.y - self.point.y > 10 || self.point.y - touchPoint.y > 10 )) {
        if (touchPoint.x < 375/ 2) {
            if (touchPoint.y - self.point.y < 0) {//++
                if ( self.player.volume - (touchPoint.y - self.point.y ) / 200 > 10) {
                    self.player.volume = 10;
                }else {
                    self.player.volume -= (touchPoint.y - self.point.y ) / 200;
                }
                
            }else { //--
                
                if ( self.player.volume - (touchPoint.y - self.point.y ) / 200 < 0) {
                    self.player.volume = 0;
                }else {
                    self.player.volume -= (touchPoint.y - self.point.y ) / 200;
                }
            }
            
        }
    }
    //进度
    if ((touchPoint.x - self.point.x > 10 || self.point.x - touchPoint.x > 10)&& touchPoint.y - self.point.y < 10) {
        if (touchPoint.x - self.point.x < 0) {
            self.videoPlayProgress.value += (touchPoint.x - self.point.x) / 10;
        }else {
            self.videoPlayProgress.value -= (self.point.x - touchPoint.x ) / 10;
        }
        [self.player seekToTime:CMTimeMake(self.videoPlayProgress.value, 1)];
        
        
    }

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    self.point = touchPoint;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
